﻿using System;
using System.Windows.Forms;

namespace Ellanet
{
    public partial class Credentials : Form // KryptonForm
    {
        private string _guiXmlPath = null;
        private string _credentialsName = null;
        private ErrorProvider ep = new ErrorProvider();

        public string CredentialsName
        {
            get
            {
                return nameTextBox.Text.Trim();
            }
        }

        public Credentials(string credentialsName, string guiXmlPath)
        {
            InitializeComponent();
            _credentialsName = credentialsName;
            _guiXmlPath = guiXmlPath;
            saveButton.Click += new EventHandler(saveButton_Click);
            this.Load += new EventHandler(Credentials_Load);
        }

        void Credentials_Load(object sender, EventArgs e)
        {
            if (_credentialsName != null)
            {
                string username = null;
                string password = null;
                new vmrunGUIXmlWrapper(_guiXmlPath).GetCredentials(_credentialsName, out username, out password);
                nameTextBox.Text = _credentialsName;
                usernameTextBox.Text = username;
                passwordTextBox.Text = password;
            }
        }

        void saveButton_Click(object sender, EventArgs e)
        {
            if (ValidateForm())
            {
                vmrunGUIXmlWrapper guiXmlWrapper = new vmrunGUIXmlWrapper(_guiXmlPath);

                if (_credentialsName != null)
                {
                    guiXmlWrapper.RemoveCredentials(_credentialsName);
                    guiXmlWrapper.UpdateCredentialsOnHostsAndGuests(_credentialsName, nameTextBox.Text.Trim());
                }

                guiXmlWrapper.AddCredentials(nameTextBox.Text.Trim(), usernameTextBox.Text, passwordTextBox.Text);
                guiXmlWrapper.SaveXml();
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        bool ValidateForm()
        {
            ep.Dispose();

            if (((nameTextBox.Text == null) || (nameTextBox.Text.Trim().Length == 0)) || (((_credentialsName == null) || (_credentialsName != nameTextBox.Text)) && (new vmrunGUIXmlWrapper(_guiXmlPath).CredentialsExists(nameTextBox.Text.Trim()))))
            {
                ep.SetError(nameTextBox, "Please specify a unique name for this managed Host.");
                nameTextBox.Select();
                return false;
            }

            if ((usernameTextBox.Text == null) || (usernameTextBox.Text.Trim().Length == 0))
            {
                ep.SetError(usernameTextBox, "Please specify a username.");
                usernameTextBox.Select();
                return false;
            }

            return true;
        }
    }
}
